package current.security.init.listener;

import java.util.Hashtable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import org.apache.log4j.Logger;

public class SessionListener implements HttpSessionListener {
	public static Hashtable<String, Object> hUserName = new Hashtable<String, Object>();
	public static Hashtable<String, Object> hcUserName = new Hashtable<String, Object>();
	public static Logger log = Logger.getLogger(SessionListener.class);
	public void sessionCreated(HttpSessionEvent se) {
		se.getSession().setMaxInactiveInterval(3600);
		log.debug("已创建新用户session -- " + se);
	}
	@SuppressWarnings("unchecked")
	public void sessionDestroyed(HttpSessionEvent se) {
		if(se.getSession().getAttribute("user") != null){
			hUserName.remove(((Map<String,Object>)se.getSession().getAttribute("user")).get("userName"));
			hcUserName.remove(((Map<String,Object>)se.getSession().getAttribute("user")).get("userName"));
		}
		log.debug("删除用户session -- " + se);
	}
	public synchronized static boolean isLogined(HttpServletRequest request,String sUserName,String cUserName) {
		boolean flag = false;
		HttpSession session = request.getSession();
		if (hUserName.containsKey(sUserName)) {
			flag = true;
			HttpSession vsession = (HttpSession) hUserName.get(sUserName);
			try {
				vsession.invalidate();
				log.debug("用户已存在，已将 - " + sUserName + " 的 session 失效并移除");
			} catch (Exception ex) {
			}
		} else {
			flag = false;
		}
		hUserName.remove(sUserName);
		hcUserName.remove(sUserName);
		hcUserName.put(sUserName, cUserName);
		hUserName.put(sUserName, request.getSession());
		log.debug("创建用户 - " + sUserName + " || session - " + session);

		return flag;
	}
	public synchronized static boolean deleteUserName(HttpSession session,String sUserName) {
		log.debug("删除用户 - " + sUserName + " || session - " + session);
		hUserName.remove(sUserName); // 删除用户
		hcUserName.remove(sUserName);
		return true;
	}
	public synchronized static boolean isOnline(HttpSession session,String sUserName) {
		boolean flag = false;
		HttpSession vsession = null;
		try {
			vsession = (HttpSession) hUserName.get(sUserName);
			if (vsession != null) {
				if (session.getId().equals(vsession.getId())) {
					flag = true;
					log.debug("同台电脑上的重复登录！！");
				} else {
					log.debug("不同电脑上的重复登录！！");
					flag = false;
				}
			}
		} catch (Exception e) {
		}
		return flag;
	}
	public static int sumPeople(){
		return hUserName.size();
	}

}
